package com.ctbri.io;

import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

import com.ctbri.util.TextFile;

import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Serializer;

public class Ex32 {
	
	public static void main(String[] args) throws Exception{
		TextFile textFile = new TextFile("channel.txt", "\\W+");
		Map<String, Integer> wordMap = new HashMap<>();
		for(String word : textFile) {
			Integer fre = wordMap.get(word);
			wordMap.put(word, fre == null ? 1 : (fre + 1));
		}
		
		Element root = new Element("words");
		for(String word : wordMap.keySet()) {
			Element wordElement = new Element("word");
			Element name = new Element("name");
			name.appendChild(word);
			Element frequence = new Element("frequence");
			frequence.appendChild(Integer.toString(wordMap.get(word)));
			wordElement.appendChild(name);
			wordElement.appendChild(frequence);
			root.appendChild(wordElement);
		}
		Document doc = new Document(root);
		Serializer serializer = new Serializer(new FileOutputStream("word.xml"), "ISO-8859-1");
		serializer.setIndent(4);
		serializer.setMaxLength(60);
		serializer.write(doc);
		serializer.flush();
	}

}
